package org.wzy.xmlg_backend.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.wzy.xmlg_backend.entity.SysUser;
import org.wzy.xmlg_backend.service.UserService;
import org.wzy.xmlg_backend.utils.Result;

import java.util.HashMap;
import java.util.Map;
import java.util.Collections;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody Map<String, String> params) {
        Map<String, Object> response = new HashMap<>();

        try {
            String token = userService.login(params.get("username"),params.get("password"));
            response.put("token", token);
            return Result.success(response);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/register")
    public Result register(@RequestBody SysUser user) {
        try {
            String token = userService.register(user);
            return Result.success(token);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/info")
    public Result getInfo(HttpServletRequest request) {
        try {
            String username = (String) request.getAttribute("username");
            if (username == null || username.isEmpty()) {
                return Result.error("无法获取用户信息");
            }

            SysUser user = userService.getUserInfo(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            // 创建包含角色数组的响应对象
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", user.getId());
            userInfo.put("username", user.getUsername());
            userInfo.put("nickname", user.getNickname());
            userInfo.put("email", user.getEmail());
            userInfo.put("phone", user.getPhone());
            userInfo.put("avatar", user.getAvatar());

            // 将角色字符串转换为数组
            String roles = user.getRoles();
            if (roles != null && !roles.isEmpty()) {
                userInfo.put("roles", Collections.singletonList(roles));
            } else {
                userInfo.put("roles", Collections.singletonList("user"));
            }

            userInfo.put("createTime", user.getCreateTime());
            userInfo.put("updateTime", user.getUpdateTime());

            return Result.success(userInfo);
        } catch (Exception e) {
            return Result.error("获取用户信息失败: " + e.getMessage());
        }
    }
}
